package com.moneycollect.example.classloader.loader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author xuhuiqian
 * @since 2022/5/25 10:23
 */
public class FileHelper {
    public static byte[] readFileToBytes(String fileName) throws IOException {
        File file = new File(fileName);
        FileInputStream in = new FileInputStream(file);

        long fileLength = file.length();
        byte[] fileContent = new byte[(int) fileLength];

        var r = in.read(fileContent);
        in.close();
        return fileContent;
    }

    public static void saveFile(byte[] content, String fileName) throws Exception {
        File file = new File(fileName);
        if (!file.exists()) {
            var createResult = file.createNewFile();
            if (!createResult) {
                throw new RuntimeException("create file fail");
            }
        }
        FileOutputStream writer = new FileOutputStream(file);
        writer.write(content);
        writer.close();
    }
}
